<script setup>
import { nextTick, ref, watch } from 'vue';
import { t } from '@/locales';
// 接收props
const props = defineProps({
  // 外部传入的字符串数据（格式：key:value;key2:value2）
  dataStr: {
    type: String,
    default: '',
  },
});

const emit = defineEmits(['close', 'save']);

// 响应式数据
const displayData = ref([]);

// 添加内容区域的ref
const modalContentRef = ref(null);

// 监听dataStr变化
watch(
  () => props.dataStr,
  (newVal) => {
    parseDataStr(newVal);
  },
  { immediate: true },
);

/**
 * 确保最后有一个空行
 */
function ensureLastEmptyRow() {
  // 如果最后一行不是空的，就添加一个空行
  const lastItem = displayData.value[displayData.value.length - 1];
  if (!lastItem || (lastItem.key || lastItem.value)) {
    displayData.value.push({
      key: '',
      value: '',
    });
  }
}

/**
 * 滚动到内容区域底部
 */
function scrollToBottom() {
  nextTick(() => {
    if (modalContentRef.value) {
      const container = modalContentRef.value;
      container.scrollTop = container.scrollHeight;
    }
  });
}

/**
 * 解析字符串数据
 * @param {string} dataStr - 外部传入的字符串数据（格式：key:value;key2:value2）
 */
function parseDataStr(dataStr) {
  if (!dataStr) {
    // 如果没有数据，添加一个空行
    displayData.value = [{
      key: '',
      value: '',
    }];
    return;
  }

  const items = dataStr.split(';');
  displayData.value = items.map((item) => {
    const [key, value] = item.split(':');
    return {
      key: key.trim(),
      value: value ? value.trim() : '',
    };
  }).filter(item => item.key);

  // 确保最后有一个空行
  ensureLastEmptyRow();

  // 解析完成后滚动到底部
  scrollToBottom();
}

/**
 * 新增一行
 */
function addItem() {
  displayData.value.push({
    key: '',
    value: '',
  });

  // 新增后滚动到底部
  scrollToBottom();
}

/**
 * 删除指定行
 * @param {number} index - 要删除的行索引
 */
function removeItem(index) {
  displayData.value.splice(index, 1);
}

// 保存数据
function handleSave() {
  // 先去重再保存
  const uniqueMap = new Map();
  displayData.value.forEach((item) => {
    if (item.key) {
      uniqueMap.set(item.key, item.value);
    }
  });

  // 重新构建数据数组
  const uniqueData = Array.from(uniqueMap, ([key, value]) => ({
    key,
    value,
  }));

  const result = uniqueData.filter(item => item.key && item.value)
    .map(item => `${item.key}:${item.value}`)
    .join(';');

  emit('save', result);
}

// 取消操作
function handleCancel() {
  emit('close');
}
</script>

<template>
  <div class="extend-info-modal">
    <!-- 内容区域 -->
    <div ref="modalContentRef" class="modal-content">
      <div v-for="(item, index) in displayData" :key="index" class="edit-item">
        <el-input
          v-model="item.key"
          :placeholder="t('user.inputKey')"
          class="edit-input"
        />
        <span class="colon">:</span>
        <el-input
          v-model="item.value"
          :placeholder="t('user.inputValue')"
          class="edit-input"
        />
        <i
          class="el-icon-delete"
          @click="removeItem(index)"
        >
          <LsIcon font-family="iconfont" value="icon-Clear" class="icon-small" />
        </i>
      </div>

      <div class="add-item">
        <el-button
          type="text"
          class="add-button"
          @click="addItem"
        >
          + {{ t('user.addColumn') }}
        </el-button>
      </div>
    </div>
    <!-- 操作按钮 -->
    <div class="modal-footer">
      <el-button class="gray-button" @click="handleCancel">
        {{ t('common.cancel') }}
      </el-button>
      <el-button
        class="primary-button"
        @click="handleSave"
      >
        {{ t('common.save') }}
      </el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
@use '@lingshu/theme-lib/scss/util.scss' as *;
.extend-info-modal {
  width: 100%;
  height: 360px;
  background-color: useThemeVar('module_bg3');

  .modal-content {
    height: 310px;
    overflow-y: auto;

    .edit-item {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      .edit-input {
        width: 160px;

        &:last-child {
          margin-right: 0;
        }
      }

      .colon {
        width: 14px;
        height: 22px;
        margin: 0 8px;
        color: useThemeVar('gray3');
      }

      .el-icon-delete {
        margin-left: 8px;
        font-size: $font-size-large;
      }
    }

    .add-item {
      text-align: center;
      margin-top: 16px;

      .add-button {
        padding: 8px 16px;
        width: 100%;
        font-size: $font-size-middle;
        color: useThemeVar('color_primary');
        border: 1px solid useThemeVar('color_primary');
        border-radius: 4px;
        background: useThemeVar('white1');

        &:hover {
          background-color: useThemeVar('button_gray_bg2');
        }
      }
    }
  }

  .modal-footer {
    padding: 26px 0 0 20px;
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    .el-button {
      padding: 8px 16px;
      font-size: $font-size-middle;
    }

    .el-button + .el-button {
      margin-left: 0px !important;
    }

    .primary-button {
      background-color: useThemeVar('color_primary');
      color: useThemeVar('white1');

      &:hover {
        background-color: useThemeVar('primary_hover');
        color: useThemeVar('white1');
      }
    }

    .gray-button {
      background-color: useThemeVar('button_gray_bg1');
      color: useThemeVar('gray1');
      border: useThemeVar('border_bg2');

      &:hover {
        background-color: useThemeVar('button_gray_bg2');
        color: useThemeVar('gray1');
      }
    }
  }
}

.icon-small {
  font-size: $font-size-large;
  color: useThemeVar('gray3');
}
</style>
